<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>游戏大厅</title>
    <link rel="stylesheet" href="css/common.css">
    <link rel="stylesheet" href="css/game_hall.css">
    <script src="js/jquery.min.js"></script>
</head>
<body>
    <div class="nav">
        五子棋对战
    </div>
    <div class="container">
        <div>
            <!-- 用户信息展示 -->
            <div id="screen"></div>
            <!-- 匹配按钮 -->
            <div id="match-button">开始匹配</div>
        </div>
    </div>

    <script>

        let passwordInput = document.querySelector('#password');
        let submitButton = document.querySelector('#submit');
        $.ajax({
                type: 'get',
                url: '/userinfo',
                success: function(body) {
                    let screen = document.querySelector('#screen');
                    let player = document.createElement('div');
                    player.innerHTML = '玩家：' + body.username;
                    let score = document.createElement('div');
                    score.innerHTML = '分数：' + body.score;
                    let totalCount = document.createElement('div');
                    totalCount.innerHTML = '游戏次数：' + body.totalCount;
                    let winCount = document.createElement('div');
                    winCount.innerHTML = '获胜场数：' + body.winCount;
                    screen.appendChild(player);
                    screen.appendChild(score);
                    screen.appendChild(totalCount);
                    screen.appendChild(winCount);
                },
                error: function() {
                    alert("获取用户信息失败！");
                }
            });

            let websocketUrl = 'ws://' + location.host + '/findMatch';
            let websocket = new WebSocket(websocketUrl);
            websocket.onopen = function() {
                console.log("onopen");
            }
            websocket.onclose = function() {
                console.log("onclose");
                // alert("和游戏大厅断开连接！");
            }
            websocket.onerror = function() {
                console.log("onerror");
            }
            //监听页面关闭事件，调用websocket的close方法
            window.onbeforeunload = function() {
                websocket.close();
            }

            //处理服务器的响应
            websocket.onmessage = function(e) {
                console.log("onmessage" + e);
                let matchButton = document.querySelector('#match-button');
                let resp = JSON.parse(e.data);
                if (!resp.ok) {
                    console.log("服务器响应：" + resp.reason);
                    if (resp.reason == "repeat connection!") {
                        alert("当前用户已经登录，请使用其他账号登录！")
                        location.replace("/login.html");
                    } else if (resp.reason == "您尚未登录，请先登录！") {
                        alert("您尚未登录，请先登录！");
                        location.replace("/login.html");
                    }
                    return;
                }
                if (resp.message == 'startMatch') {
                    console.log("正在进行匹配！");
                    matchButton.innerHTML = '停止匹配';
                } else if (resp.message == 'stopMatch') {
                    matchButton.innerHTML = '开始匹配';
                } else if (resp.message == 'matchSuccess') {
                    console.log("匹配成功！");
                    alert("匹配成功！");
                    location.replace('/game_room.html');
                } else {
                    console.log('响应出错！ message = ' + resp.message);
                }
            }

            // 发送 匹配/停止匹配 请求
            let matchButton = document.querySelector('#match-button');
            matchButton.onclick = function() {
                //确认websocket连接
                if (websocket.readyState == websocket.OPEN) {
                    if (matchButton.innerHTML == '开始匹配') {
                        console.log("开始匹配");
                        websocket.send(JSON.stringify({
                            message: 'startMatch',
                        })) ;
                    } else if (matchButton.innerHTML == '停止匹配') {
                        console.log("停止匹配");
                        websocket.send(JSON.stringify({
                            message: 'stopMatch',
                        })) ;
                    }
                } else {
                    alert("连接已断开，请重新登录！");
                    location.replace('/login.html');
                }
            }
    </script>
</body>
</html>